package com.avcdata.aoscustommade.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by c.c on 2017/3/1.
 * 万能适配器用ViewHolder
 */
public class ViewHolder {
    //现在对于int作为键的官方推荐用SparseArray替代HashMap
    private final SparseArray<View> views;
    private View convertView;

    private ViewHolder(Context mContext, View convertView) {
        this.views = new SparseArray<View>();
        this.convertView = convertView;
        convertView.setTag(this);
    }

    public static ViewHolder get(Context mContext, View convertView, ViewGroup parent, int resId) {
        if (convertView == null) {
            LayoutInflater factory = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = factory.inflate(resId, parent, false);
            return new ViewHolder(mContext, convertView);
        }
        return (ViewHolder) convertView.getTag();
    }

    @SuppressWarnings("unchecked")
    public <T extends View> T findViewById(int resourceId) {
        View view = views.get(resourceId);
        if (view == null) {
            view = convertView.findViewById(resourceId);
            views.put(resourceId, view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return convertView;
    }

    public void setConvertView(View convertView) {
        this.convertView = convertView;
    }

}
